$(function () {
    /* 初始化加载数据表 */
	$('#operateClaszDialog').hide();
	$('#manageStudentsDialog').hide();
	$('#manageTeachersDialog').hide();
    initClaszGridData();
    initOther();
});

function initClaszGridData() {
    $('#claszDataGrid').datagrid({
        fitColumns: true,
        fit: true,
        idField: 'Id',
        sortName: 'Id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: true,
        pagination: true,
        border: false,
        url: "clasz/all",
        toolbar: '#tb',
//        toolbar: [
//            {
//                text: '新增',
//                iconCls: 'icon-add',
//                handler: function () {
//                    showOperateClaszDialog("新增");
//                }
//            },
//            '-',
//            {
//                text: '刷新',
//                iconCls: 'icon-reload',
//                handler: function () {
//                    gridReload($('#claszDataGrid'));
//                }
//            }
//        ],
//        columns: [
//            [
//                {field: 'name', title: '名称', align: 'center', width: 50},
//                {field: 'type', title: '班级类型', align: 'center', width: 40,
//                    formatter: function (value, row, index) {
//                        return classtype[value];
//                    }
//                },
//                {field: 'createYear', title: '年级', align: 'center', width: 80,
//                    formatter: function (value, row, index) {
//                        return value;
//                    }
//                },
//                {field: 'operation', title: '操作', align: 'center', width: 80,
//                    formatter: function (value, row, index) {
//                        var spanId = "clasz_" + row.id;
//                        return "<button onclick='showOperateClaszDialog(\"修改\", " + index + ");'>修改</button>" +
//                            "<button onclick='showDeleteClaszDialog(" + index + ");'>删除</button>" +
//                            "<button onclick='showManageStudentsDialog(" + index + ");'>管理班级学生</button>" +
//                            "<button onclick='showManageTeachersDialog(" + index + ");'>分配老师</button>";
//                    }
//                }
//            ]
//        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onLoadSuccess: function() {
        	changeStyle();
        	$('#operateClaszDialog').show();
        	$('#manageStudentsDialog').show();
        	$('#manageTeachersDialog').show();
        }
    });
    setDataGridPager($('#claszDataGrid'));
}

//============================ //
function changeStyle() {
	$('.re').linkbutton({  
	    iconCls: 'icon-remove',
	    plain: true
	});  
	$('.up').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
	$('.fp').linkbutton({  
	    iconCls: 'icon-edit',
	    plain: true
	});  
}

function initOther() {
    extendValiateboxType();
    $('#type').combobox({
        valueField: 'id',
        textField: 'text',
        panelHeight: 'auto',
        data: [
            {
                "id": 0,
                "text": classtype[0]
            },
            {
                "id": 1,
                "text": classtype[1]
            }
        ]
    });
}

function showOperateClaszDialog(operateName, index) {
    $('#oldIdNo').remove();
    $('#oldType').remove();
    $('#operateClaszDialog').dialog({
        title: operateName + "班级信息",
        width: 250,
        height: 180,
        modal: true,
        buttons: [
            {
                text: operateName,
                handler: function (params) {
                    operateClasz(operateName);
                }
            },
            {
                text: '取消',
                handler: function () {
                    $('#operateClaszDialog').dialog('close');
                }
            }
        ]
    });
    clearOldData();
    if (operateName == '修改') {
        var clasz = getSelectedRow('claszDataGrid', index);
        $("#id").val(clasz.id);
        $("#name").val(clasz.name);
        $("#type").combobox('select', clasz.type);
        $('#operateClaszDialog').append("<span id='oldIdNo'>" + clasz.name + "</span><span id='oldType'>" + clasz.type + "</span>");
    	$('#createYear').val(clasz.createYear);
    } else {
    	$('#createYear').val(new Date().getFullYear());
    }
}

function clearOldData() {
    $("#id").val("");
    $("#name").val("");
    $("#type").combobox('setValue', 0);
}
function inValidYear(element){
	var sTest=/^(\d{4})$/;
	if(!sTest.test(element.val())){
		element.focus();
		element.select();
		return false;
	}
	return true;
}

function operateClasz(operationName) {
    var $name = $('#name');
	if ($.trim($name.val()).length == 0) {
		$.messager.alert("警告", "请确保红色*内容不为空！", "warning");
		return;
	}
	if (!inValidYear($('#createYear'))) {
		$.messager.alert("警告", "请确保年级输入正确年份！", "warning");
		return;
	}
    var tempUrl = "clasz/add";
    if (operationName === '修改') {
        tempUrl = "clasz/update";
    } else {
        $("#id").val(-999);
    }
	if ($('#oldIdNo').text() != null && $('#oldIdNo').text() == $("#name").val()) {
    	if ($("#type").combobox('getValue') != $('#oldType').text()) {
            $.messager.confirm("警告", "修改班级类型，将会首先删除已经分配的班级学生与教师？！", function(r){
                if (r){
                    $.ajax({
                        type: 'POST',
                        data: {
                            "id": $("#id").val(),
                            "name": $("#name").val(),
                            "createYear": $('#createYear').val(),
                            "type": $("#type").combobox('getValue'),
                            "oldType": $('#oldType').text()},
                        url: tempUrl,
                        dataType: "json",
                        cache: false,
                        error: function (jqXHR, textStatus, errorThrown) {
                            $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        },
                        success: function (data) {
                            if (true == data.result) {
                                $.messager.alert("操作提示", "班级信息操作完成！", "info", function () {
                                    $('#operateClaszDialog').window("close");
                                    gridReload($('#claszDataGrid'));
                                });
                            }
                        }
                    });
                }
            });
    	} else {
    		$.ajax({
    			type: 'POST',
    			data: {
    				"id": $("#id").val(),
    				"name": $("#name").val(),
    				"createYear": $('#createYear').val(),
    				"type": $("#type").combobox('getValue')},
    				url: tempUrl,
    				dataType: "json",
    		        cache: false,
    				error: function (jqXHR, textStatus, errorThrown) {
    					$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
    				},
    				success: function (data) {
    					if (true == data.result) {
    						$.messager.alert("操作提示", "班级信息操作完成！", "info", function () {
    							$('#operateClaszDialog').window("close");
    							gridReload($('#claszDataGrid'));
    						});
    					}
    				}
    		});
    	}
    }  
	else {
		$.ajax({
	        type: 'POST',
	        data: { "claszName": $("#name").val() },
	        url: "clasz/exists",
	        dataType: "json",
	        cache: false,
	        success: function (data) {
	            if (true == data.result) {
	        		$.messager.alert("警告", "班级已经存在！", "warning");
	            } else {
	                $.ajax({
	                    type: 'POST',
	                    data: {
	                        "id": $("#id").val(),
	                        "name": $("#name").val(),
	                        "createYear": $('#createYear').val(),
	                        "type": $("#type").combobox('getValue')},
	                    url: tempUrl,
	                    dataType: "json",
	                    cache: false,
	                    error: function (jqXHR, textStatus, errorThrown) {
	                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
	                    },
	                    success: function (data) {
	                        if (true == data.result) {
	                            $.messager.alert("操作提示", "班级信息操作完成！", "info", function () {
	                                $('#operateClaszDialog').window("close");
	                                gridReload($('#claszDataGrid'));
	                            });
	                        }
	                    }
	                });
	            }
	        }
	    });
	}
}

function showDeleteClaszDialog(index) {
    $.messager.confirm("警告", "确定删除选中班级？", function (data) {
        if (data) {
        	var clasz = getSelectedRow('claszDataGrid', index);
        	$.ajax({
        		type: 'POST',
        		data: {
        			"claszId": clasz.id,
        			"claszType": clasz.type
        		},
        		url: "clasz/remove",
        		dataType: "json",
        		cache: false,
        		error: function (jqXHR, textStatus, errorThrown) {
        			$.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
        		},
        		success: function (data) {
        			if (true == data.result) {
    					gridReload($('#claszDataGrid'));
        			} else {
                        $.messager.alert("操作提示", "删除班级信息异常！");
                    }
        		}
        	});
        }
    });
}

function showManageStudentsDialog(index) {
	$('#manageStudentsDialog').show();
    var clasz = getSelectedRow('claszDataGrid', index);
    $('#currentClaszId').val(clasz.id);
    $('#currentClaszType').val(clasz.type);
    var tempUrl = "student/search-by-studyclass?studyClass=";
    var searchNotInClassUrl = "student/search-not-in-studyClass";
    if (clasz.type == 1) {
        tempUrl = "student/search-by-adminclass?adminClass=";
        searchNotInClassUrl = "student/search-not-in-adminClass";
    }
    $('#manageStudentsDialog').dialog({
        title: "班级[" + clasz.name + "] --> 学生管理",
        width: 842,
        height: 400,
	    iconCls: 'icon-edit',
        modal: true,
        onClose: function() {
        	$('#studentsInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        	$('#studentsOutClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        }
    });
    $('#studentsInClaszDataGrid').datagrid({
        title: "已分配学生",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        pagination: true,
        border: true,
        url: tempUrl + clasz.id,
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'studentNumber', title: '学号', align: 'center', width: 30},
                {field: 'name', title: '姓名', align: 'center', width: 30},
                {field: 'sex', title: '性别', align: 'center', width: 10,
                    formatter: function (value, row, index) {
                        return sex[value];
                    }
                },
                {field: 'nation', title: '民族', align: 'center', width: 10,
                    formatter: function (value, row, index) {
                        return nation[value - 1];
                    }
                }
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }
    });
    $('#studentsInClaszDataGrid').datagrid('getPager').pagination({
        pageSize: 10,//每页显示的记录条数，默认为10
        pageList: [10, 20, 30],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages} 页',
        displayMsg: '共 {total} 条'
    });

    $('#studentsOutClaszDataGrid').datagrid({
        title: "未分配学生",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        pagination: true,
        border: true,
        url: searchNotInClassUrl,
        toolbar: '#tb-fs',
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'studentNumber', title: '学号', align: 'center', width: 30},
                {field: 'name', title: '姓名', align: 'center', width: 30},
                {field: 'sex', title: '性别', align: 'center', width: 10,
                    formatter: function (value, row, index) {
                        return sex[value];
                    }
                },
                {field: 'nation', title: '民族', align: 'center', width: 10,
                    formatter: function (value, row, index) {
                        return nation[value - 1];
                    }
                }
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        }
    });
    $('#studentsOutClaszDataGrid').datagrid('getPager').pagination({
        pageSize: 10,//每页显示的记录条数，默认为10
        pageList: [10, 20, 30],//可以设置每页记录条数的列表
        beforePageText: '第',//页数文本框前显示的汉字
        afterPageText: '页    共 {pages} 页',
        displayMsg: '共 {total} 条'
    });
}

// 从班级中移除学生
function removeStudentsFromCLasz() {
    var ids = [];
    var rows = $('#studentsInClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将选中的学生移除此班级", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "clasz/" + $('#currentClaszId').val() + "/removestudents?claszType=" + $('#currentClaszType').val() + "&studentIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#studentsInClaszDataGrid').datagrid('unselectAll');
                        $('#studentsOutClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "移除完成！", "info", function () {
                                reloadStudentsInClasz();
                                $('#studentsInClaszDataGrid').datagrid('unselectAll');
                                $('#studentsOutClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中学生！");
    }
}

// 从班级中移除学生
function addStudentsToCLasz() {
    var ids = [];
    var rows = $('#studentsOutClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将选中的学生添加到此班级", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "clasz/" + $('#currentClaszId').val() + "/addstudents?claszType=" + $('#currentClaszType').val() + "&studentIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#studentsInClaszDataGrid').datagrid('unselectAll');
                        $('#studentsOutClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "添加完成！", "info", function () {
                                reloadStudentsInClasz();
                                $('#studentsInClaszDataGrid').datagrid('unselectAll');
                                $('#studentsOutClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中学生！");
    }
}

function reloadStudentsInClasz() {
    $('#studentsInClaszDataGrid').datagrid('reload');
    $('#studentsOutClaszDataGrid').datagrid('reload');
}
//============================================
//============================================
function showManageTeachersDialog(index) {
	$('#manageTeachersDialog').show();
    var clasz = getSelectedRow('claszDataGrid', index);
    $('#currentClaszId').val(clasz.id);
    $('#currentClaszType').val(clasz.type);
    var tempUrl = "clasz/" + $('#currentClaszId').val() + "/all-teachers";
    var searchNotInClassUrl = "clasz/not-in/" + $('#currentClaszId').val() + "/teachers";
    $('#manageTeachersDialog').dialog({
        title: "班级[" + clasz.name + "] --> 教师管理",
        width: 842,
        height: 400,
	    iconCls: 'icon-edit',
        modal: true,
        onClose: function() {
        	$('#teachersInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        	$('#teachersNotInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        }
    });
    $('#teachersInClaszDataGrid').datagrid({
        title: "已分配教师",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        border: true,
        url: tempUrl,
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'name', title: '姓名', align: 'center', width: 40},
                {field: 'sex', title: '性别', align: 'center', width: 15,
                    formatter: function (value, row, index) {
                        return sex[value];
                    }
                },
                {field: 'nation', title: '民族', align: 'center', width: 20,
                    formatter: function (value, row, index) {
                        return nation[value - 1];
                    }
                },
                {field: 'subject', title: '科目', align: 'center', width: 40}
//                {field: 'grade', title: '任课班级', align: 'center', width: 40}
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onClose: function() {
        	$('#teachersInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        }
    });

    $('#teachersNotInClaszDataGrid').datagrid({
        title: "未分配教师",
        fitColumns: true,
        fit: true,
        idField: 'id',
        sortName: 'id',
        sortOrder: 'desc',
        rownumbers: true,
        singleSelect: false,
        border: true,
        url: searchNotInClassUrl,
        toolbar: '#tb-ft',
        columns: [
            [
                {field: 'id', hidden: true}, // datagrid多选 getSelections ，必须使用idFiled这个字段
                {field: 'ck', align: 'center', width: 10, checkbox: true},
                {field: 'name', title: '姓名', align: 'center', width: 40},
                {field: 'sex', title: '性别', align: 'center', width: 15,
                    formatter: function (value, row, index) {
                        return sex[value];
                    }
                },
                {field: 'nation', title: '民族', align: 'center', width: 20,
                    formatter: function (value, row, index) {
                        return nation[value - 1];
                    }
                },
                {field: 'subject', title: '科目', align: 'center', width: 40}
                //                {field: 'grade', title: '任课班级', align: 'center', width: 40}
            ]
        ],
        rowStyler: function(index,row){  
            if (index % 2 == 1){  
                return 'background-color:#FFF8DC;';  
            }  
        },
        onClose: function() {
        	$('#teachersNotInClaszDataGrid').datagrid('loadData', { total: 0, rows: [] });
        }
    });
}

// 从班级中移除老师
function removeTeachersFromCLasz() {
    var ids = [];
    var rows = $('#teachersInClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将选中的教师移除此班级", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "clasz/" + $('#currentClaszId').val() + "/removeteachers?teacherIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#teachersInClaszDataGrid').datagrid('unselectAll');
                        $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "移除完成！", "info", function () {
                                reloadTeachersInClasz();
                                $('#teachersInClaszDataGrid').datagrid('unselectAll');
                                $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中教师！");
    }
}

// 从班级中移除教师
function addTeachersToCLasz() {
    var ids = [];
    var rows = $('#teachersNotInClaszDataGrid').datagrid('getSelections');
    for (var i = 0; i < rows.length; i++) {
        ids.push(rows[i].id);
    }
    if (ids.length > 0) {
        $.messager.confirm("提示", "是否将选中的教师分配到此班级", function (data) {
            if (data) {
                $.ajax({
                    type: 'GET',
                    url: "clasz/" + $('#currentClaszId').val() + "/addteachers?teacherIdsStr=" + ids,
                    dataType: "json",
                    cache: false,
                    error: function (jqXHR, textStatus, errorThrown) {
                        $.messager.alert("操作提示", "数据保存异常:[" + jqXHR.statusText + "]", "error");
                        $('#teachersInClaszDataGrid').datagrid('unselectAll');
                        $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
                    },
                    success: function (data) {
//                        if (true == data.result) {
//                            $.messager.alert("操作提示", "添加完成！", "info", function () {
                                reloadTeachersInClasz();
                                $('#teachersInClaszDataGrid').datagrid('unselectAll');
                                $('#teachersNotInClaszDataGrid').datagrid('unselectAll');
//                            });
//                        }
                    }
                });
            }
        });
    } else {
        $.messager.alert("提示", "请选中教师！");
    }
}

function reloadTeachersInClasz() {
    $('#teachersInClaszDataGrid').datagrid('reload');
    $('#teachersNotInClaszDataGrid').datagrid('reload');
}

function searchClaszByName() {
	if (undefined == $("#sName").val() || "" == $("#sName").val() || $.trim($("#sName").val()).length == 0) {
		$('#claszDataGrid').datagrid({
			url:'clasz/all'
		});
	} else {
		$('#claszDataGrid').datagrid({
			url:'clasz/clasz-by-name',
		    queryParams:{ name: $("#sName").val()}
		});
	}
}

function searchTeacherByName() {
	if (undefined == $("#teacher_sName").val() || "" == $("#teacher_sName").val() || $.trim($("#teacher_sName").val()).length == 0) {
		$('#teachersNotInClaszDataGrid').datagrid({
			url:"clasz/not-in/" + $('#currentClaszId').val() + "/teachers"
		});
	} else {
		$('#teachersNotInClaszDataGrid').datagrid({
			url: "clasz/not-in/" + $('#currentClaszId').val() + "/teachers-byname",
		    queryParams:{ name: $("#teacher_sName").val()}
		});
	}
}

function searchStudentByName() {
    var searchNotInClassUrl = "student/search-not-in-studyClass";
    if ($('#currentClaszType').val() == 1) {
        searchNotInClassUrl = "student/search-not-in-adminClass";
    }
	if (undefined == $("#student_sName").val() || "" == $("#student_sName").val() || $.trim($("#student_sName").val()).length == 0) {
		$('#studentsOutClaszDataGrid').datagrid({
			url:searchNotInClassUrl
		});
	} else {
	    var url = "student/search-not-in-studyClass-byname";
	    if ($('#currentClaszType').val() == 1) {
	    	url = "student/search-not-in-adminClass-byname";
	    }
		$('#studentsOutClaszDataGrid').datagrid({
			url: url,
		    queryParams:{ name: $("#student_sName").val()}
		});
	}
}